<template>
  <div class="LoginOrReGisterContainer">
    <WindowTab :full="false" :mini="false" obj="login"></WindowTab>
    <div class="w-full flex-1 flex flex-col items-center px-6">
      <!-- 头像 -->
      <n-avatar :size="108" :src="loginForm.avatar ? loginForm.avatar : Logo" circle class="mb-4" />
      <!-- 表单 -->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="LoginRules"
        aria-autocomplete="none"
        status-icon
        style="color: #303133"
        class="mb-3"
      >
        <el-form-item prop="name" style="position: relative">
          <el-input v-model="loginForm.name" placeholder="请输入用户名" @input="ChangeAccount">
            <template #suffix>
              <div
                v-if="loginHistory.length != 0"
                class="text-base cursor-pointer"
                @click="selectStatus = !selectStatus"
              >
                <component :is="RenderIcon(selectStatus ? ChevronUpOutline : ChevronDown, 'text-base')"></component>
              </div>
            </template>
          </el-input>
          <div v-if="selectStatus && loginHistory.length != 0" class="accountSelect" @mouseleave="selectStatus = false">
            <div v-for="item in loginHistory" class="accountSelectItem">
              <div class="flex-1 flex flex-row items-center gap-2" @click="SelectAccount(item.name, item.avatar)">
                <n-avatar :src="item.avatar" circle />
                <span class="text-base">{{ item.name }}</span>
              </div>
              <CloseOutline class="w-[20px] h-[20px]" @click="RemoveLoginHistory(item.name)" />
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="loginForm.password" placeholder="请输入密码" type="password" />
        </el-form-item>

        <el-form-item prop="captchaVal">
          <div class="flex flex-row jus-between items-center gap-4">
            <el-input v-model="loginForm.captchaVal" placeholder="请输入验证码" />
            <el-image :src="captchaImage" class="w-[140px] h-[38px] cursor-pointer" @click="Captcha" />
          </div>
        </el-form-item>

        <el-form-item prop="rememberMe">
          <div class="w-full flex flex-row justify-between items-center text-xs">
            <el-checkbox v-model="loginForm.rememberMe">记住我</el-checkbox>
            <p>
              还没有账号？<span class="text-sky-500 ml-2 cursor-pointer font-bold" @click="GoRegister">立即注册</span>
            </p>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button :loading="loading" class="w-full" type="primary" @click="LoginSubmit(loginFormRef)">
            登录
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 提示 -->
      <p class="text-xs text-[#303133]">&copy; 2025 Abstract UI - All Rights Reserved.</p>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref, toRaw } from "vue";
import type { ILoginHistoryItem, IUserLoginParams } from "@/types/login.ts";
import { GetCaptcha } from "@/api/user";
import { useUser } from "@/store/modules/user.ts";
import { useSystem } from "@/store/modules/system";
import { StoreMap } from "@/tactics/store";
import { LoginRules, Logo, RemoveAllCache, RenderIcon } from "@/utils/common";
import { NAvatar } from "naive-ui";
import { ElForm, ElMessage } from "element-plus";
import WindowTab from "@/components/WindowTab/index.vue";
import { ChevronDown, ChevronUpOutline, CloseOutline } from "@vicons/ionicons5";

const user = useUser();
const system = useSystem();
const loginFormRef = ref();
let captchaImage = ref<string>("");
let loading = ref<boolean>(false);
let loginHistory = ref<ILoginHistoryItem[]>([]);
let selectStatus = ref(false);
let loginForm = reactive<IUserLoginParams>({} as IUserLoginParams);

// 登录提交
async function LoginSubmit(formEl: InstanceType<typeof ElForm> | undefined) {
  if (!formEl) return;
  loading.value = true;
  try {
    await formEl.validate();
    await user.UserLogin(toRaw(loginForm));
    ElMessage({
      type: "success",
      message: "登录成功",
      onClose: () => {
        loading.value = false;
        window.electronApi.login();
      },
    });
    if (loginForm.rememberMe) {
      AddLoginHistory(user.avatar!);
    }
  } catch (error: any) {
    RemoveAllCache();
    loading.value = false;
    ElMessage.error({
      message: error.message || "登录过程出错",
    });
  }
}

// 跳转到注册
function GoRegister() {
  window.electronApi.register({
    title: "register",
    path: "register",
    width: 330,
    height: 460,
    frame: false,
  });
}

// 获取验证码
async function Captcha() {
  let res: any = await GetCaptcha();
  if (!res) return;
  loginForm.captchaId = res.captchaId;
  captchaImage.value = import.meta.env.VITE_API_Captcha + res.captcha_url;
}

// 添加记录历史
function AddLoginHistory(avatar: string) {
  const name = loginForm.name;
  const rememberMe = loginForm.rememberMe;
  const index = loginHistory.value.findIndex((item) => item.name === name);
  if (index !== -1) {
    const [existing] = loginHistory.value.splice(index, 1);
    loginHistory.value.unshift(existing);
  } else {
    loginHistory.value.unshift({ name, avatar, rememberMe });
  }
  StoreMap["localStorage"].setItem("uh", toRaw(loginHistory.value));
}

// 加载登录历史
function InitLoginHistory() {
  const info = StoreMap["localStorage"].getItem("uh");
  if (!Array.isArray(info) || info.length === 0) return;
  loginHistory.value = info;
  const { name, avatar, rememberMe } = info[0];
  loginForm.name = name;
  loginForm.avatar = avatar;
  loginForm.rememberMe = rememberMe;
}

// 选择账号
function SelectAccount(name: string, avatar: string) {
  loginForm.name = name;
  loginForm.avatar = avatar;
  selectStatus.value = false;
}

// 移除登录账号历史
function RemoveLoginHistory(name: string) {
  if (loginForm.name === name) {
    Object.assign(loginForm, { name: "", avatar: "" });
  }
  loginHistory.value = loginHistory.value.filter((item) => item.name !== name);
  if (!loginHistory.value.length) {
    Object.assign(loginForm, { name: "", avatar: "" });
    selectStatus.value = false;
  }
  StoreMap["localStorage"].setItem("uh", toRaw(loginHistory.value));
}

// 如果输入的用户名在历史记录中存在，则更新头像
function ChangeAccount(name: string) {
  const account = loginHistory.value.find((item) => item.name === name);
  if (account) {
    loginForm.avatar = account.avatar;
  } else {
    loginForm.avatar = Logo;
  }
}
system.GetUserLocation();
InitLoginHistory();
Captcha();
</script>

<style lang="scss" scoped>
@import url("@/assets/css/loginOrRegster/index.css");

.accountSelect {
  position: absolute;
  width: 285px;
  max-height: 100px;
  top: 43px;
  left: 0px;
  background-color: rgb(255, 255, 255, 0.3);
  backdrop-filter: blur(20px);
  z-index: 999;
  border-radius: 4px;
  padding: 5px;

  .accountSelectItem {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 5px 10px;
    cursor: pointer;

    &:hover {
      background-color: rgb(0, 0, 0, 0.2);
      border-radius: 4px;
    }
  }
}
</style>
